package com.gantang.lowcode.controller;

import com.gantang.lowcode.configuration.MetabaseProperties;
import com.gantang.lowcode.dto.Resource;
import com.gantang.lowcode.req.EmbedReq;
import com.gantang.lowcode.utils.MetaBaseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.*;


@Slf4j
@RestController
@RequestMapping("metabase")
public class MetaBaseController {
    @Autowired
    private MetabaseProperties metabaseProperties;
    @Autowired
    private RestTemplate restTemplate;

    // 获取嵌入仪表盘列表
    @PostMapping("/dashboards")
    public List<Resource> dashboards() {
        String json = fetchData("/api/dashboard/embeddable");
        return MetaBaseUtil.extractResources(json);
    }

    // 获取嵌入问题列表
    @PostMapping("/cards")
    public List<Resource> cards() {
        String json = fetchData("/api/card/embeddable");
        return MetaBaseUtil.extractResources(json);
    }

    private String fetchData(String apiUrl) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("x-api-key", metabaseProperties.getApiKey()); // 设置 API 密钥
        HttpEntity<String> entity = new HttpEntity<>(headers);

        ResponseEntity<String> response = restTemplate.exchange(
                metabaseProperties.getHost() + apiUrl,
                HttpMethod.GET,
                entity,
                String.class
        );
        return response.getBody();
    }

    // 获取指定嵌入仪表盘URL
    @PostMapping("dashboardUrlById")
    public String dashboardUrlById(@RequestBody EmbedReq embedReq) {
        String token = MetaBaseUtil.generateToken(embedReq, metabaseProperties.getEmbedSecretKey());
        log.info(embedReq + " token = " + token);
        return metabaseProperties.getHost() + "/embed/dashboard/" + token;
    }

    // 获取指定嵌入问题URL
    @PostMapping("questionUrlById")
    public String questionUrlById(@RequestBody EmbedReq embedReq) {
        String token = MetaBaseUtil.generateToken(embedReq,
                metabaseProperties.getEmbedSecretKey());
        log.info(embedReq + " token = " + token);
        return metabaseProperties.getHost() + "/embed/question/" + token;
    }
}
